﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Media;
using System.Xml.Linq;
using Common;
using DbControl;
using LiveCharts;
using LiveCharts.Definitions.Charts;
using LiveCharts.Maps;
using LiveCharts.WinForms;
using LiveCharts.Wpf;
using Models;
using NVRCsharpDemo;
using Brushes = System.Windows.Media.Brushes;

namespace CentralMonitoring
{
    public partial class MonitorFrm : Form
    {
        public MonitorFrm()
        {
            InitializeComponent();
            initParasChart();
            CameraDeviceInit();
        }
        private string m_dvCode;
        /// <summary>
        /// 重新加载按设备查看详细信息
        /// </summary>
        /// <param name="deviceCode"></param>
        public void ReLoadUI(string deviceCode)
        {
            m_dvCode = deviceCode;            
            Devicelist devicelist = session.m_dvList.Find(t => t.devCode == m_dvCode);
            ShowDeviceInformateion(devicelist);
            sensordatas sensordatas = OprUI.GetMontoringInfo(m_dvCode);
            ShowSensorInformation(sensordatas);
            LoadCurveData(m_dvCode);
            GloabalEvent.SensorOnPublic += GloabalEvent_SensorOnPublic;
        }
        /// <summary>
        /// 实时刷新
        /// </summary>
        /// <param name="obj"></param>
        private void GloabalEvent_SensorOnPublic(sensordatas obj)
        {
            if(obj != null)
            {
                if(obj.device_code== m_dvCode)
                {
                    UpdateDataByNewVo(obj);
                    ShowChartData();
                }
            }
        }
        #region 曲线信息
        List<string> xTime = new List<string>();
        /// <summary>
        /// chart1 粘温
        /// </summary>
        ChartValues<decimal> Wdlst = new ChartValues<decimal>();
        ChartValues<decimal> Ndlst = new ChartValues<decimal>();
        /// <summary>
        /// chart2 水分
        /// </summary>        
        ChartValues<decimal> ppmlst = new ChartValues<decimal>();
        ChartValues<decimal> dclst = new ChartValues<decimal>();
        /// <summary>
        /// chart3 铁磁
        /// </summary>      
        ChartValues<decimal> Fe1lst = new ChartValues<decimal>();
        ChartValues<decimal> Fe2lst = new ChartValues<decimal>();
        ChartValues<decimal> Fe3lst = new ChartValues<decimal>();
        ChartValues<decimal> Fe4lst = new ChartValues<decimal>();
        ChartValues<decimal> Fe5lst = new ChartValues<decimal>();
        ChartValues<decimal> Fe6lst = new ChartValues<decimal>();
        ChartValues<decimal> Fe7lst = new ChartValues<decimal>();
        ChartValues<decimal> Fe8lst = new ChartValues<decimal>();
        ChartValues<decimal> Fe9lst = new ChartValues<decimal>();
        ChartValues<decimal> Fe10lst = new ChartValues<decimal>();

        ChartValues<decimal> NFe1lst = new ChartValues<decimal>();
        ChartValues<decimal> NFe2lst = new ChartValues<decimal>();
        ChartValues<decimal> NFe3lst = new ChartValues<decimal>();
        ChartValues<decimal> NFe4lst = new ChartValues<decimal>();

        private delegate void ShowChartDelegate();//显示曲线信息
        private void ShowChartData()
        {
            if (this.InvokeRequired)
                this.BeginInvoke(new ShowChartDelegate(ShowChartData));
            else
            {
                myRefreshChartCst();
                myRefreshchartPpm();
                myRefreshchartFe();
            }
        }
        private void myRefreshChartCst()
        {
            carChartVisTemper.Series.Clear();
            carChartVisTemper.AxisX.Clear();
            carChartVisTemper.AxisY.Clear();
            carChartVisTemper.Series.Add(new LineSeries
            {
                Values = Wdlst,
                //DataLabels = true,
                Title = "温度",
                LineSmoothness = 1,
                LabelPoint = (point => point.Y.ToString()),
                ScalesYAt = 0
            });
            carChartVisTemper.Series.Add(new LineSeries
            {
                Values = Ndlst,
                //DataLabels = true,
                Title = "粘度",
                LineSmoothness = 1,
                LabelPoint = (point => point.Y.ToString()),
                ScalesYAt = 1
            });

            carChartVisTemper.AxisY.Add(new Axis
            {
                Foreground = System.Windows.Media.Brushes.DodgerBlue,
                Title = "温度",
                MinValue = 0
            });
            carChartVisTemper.AxisY.Add(new Axis
            {
                Foreground = System.Windows.Media.Brushes.IndianRed,
                Title = "粘度",
                MinValue = 0,
                Position = AxisPosition.RightTop,               

            });
            carChartVisTemper.AxisX.Add(new Axis
            {
                Labels = xTime,
                //LabelFormatter=val=>val.ToString()
                LabelsRotation = 20,
                Separator = new Separator { Step = 2 }
            });

        }
        private void myRefreshchartPpm()
        {
            carChartOils.Series.Clear();
            carChartOils.AxisY.Clear();
            carChartOils.AxisX.Clear();
            carChartOils.Refresh();
            carChartOils.Series.Add(new LineSeries
            {
                Values = ppmlst,
                //DataLabels = true,
                Title = "水分",
                LineSmoothness = 1,
                LabelPoint = (point => point.Y.ToString()),
                ScalesYAt = 0
            });
            carChartOils.Series.Add(new LineSeries
            {
                Values = dclst,
                //DataLabels = true,
                Title = "介电常数",
                LineSmoothness = 1,
                LabelPoint = (point => point.Y.ToString()),
                ScalesYAt = 1
            });

            carChartOils.AxisY.Add(new Axis
            {
                Foreground = System.Windows.Media.Brushes.DodgerBlue,
                Title = "水分",
                MinValue = 0
            });
            carChartOils.AxisY.Add(new Axis
            {
                Foreground = System.Windows.Media.Brushes.IndianRed,
                Title = "介电常数",
                MinValue = 0,
                Position = AxisPosition.RightTop
            });
            carChartOils.AxisX.Add(new Axis
            {
                Labels = xTime,
                LabelsRotation = 20,
                Separator = new Separator { Step = 2 }
            });
        }
        private void myRefreshchartFe()
        {
            #region Fe
            carChartFe.Series.Clear();
            carChartFe.AxisX.Clear();
            carChartFe.AxisY.Clear();
            carChartFe.Series.Add(new LineSeries
            {
                Values = Fe1lst,
                //DataLabels = true,
                Title = "Fe1",
                LineSmoothness = 1,
                LabelPoint = (point => point.Y.ToString())               
            });
            carChartFe.Series.Add(new LineSeries
            {
                Values = Fe2lst,
                //DataLabels = true,
                Title = "Fe2",
                LineSmoothness = 1,
                LabelPoint = (point => point.Y.ToString()),                
            });
            carChartFe.Series.Add(new LineSeries
            {
                Values = Fe3lst,
                //DataLabels = true,
                Title = "Fe3",
                LineSmoothness = 1,
                LabelPoint = (point => point.Y.ToString()),
            });
            carChartFe.Series.Add(new LineSeries
            {
                Values = Fe4lst,
                //DataLabels = true,
                Title = "Fe4",
                LineSmoothness = 1,
                LabelPoint = (point => point.Y.ToString()),
            });
            carChartFe.Series.Add(new LineSeries
            {
                Values = Fe5lst,
                //DataLabels = true,
                Title = "Fe5",
                LineSmoothness = 1,
                LabelPoint = (point => point.Y.ToString()),
            });

            carChartFe.AxisY.Add(new Axis
            {
                Foreground = System.Windows.Media.Brushes.DodgerBlue,
                Title = "铁磁颗粒",
                MinValue = 0
            });         
            carChartFe.AxisX.Add(new Axis
            {
                Labels = xTime,
                LabelsRotation = 15,
                Separator = new Separator { Step = 2 }
            });

            #endregion
        }
        private void UpdateDataByNewVo(sensordatas data)
        {
            if (xTime.Count < 60)
            {
                xTime.Add(data.create_time.Value.ToString("yyyy-MM-dd HH:mm:ss"));
            }
            else
            {
                xTime.RemoveAt(0);
                xTime.Add(data.create_time.Value.ToString("yyyy-MM-dd HH:mm:ss"));
            }
            if (Wdlst.Count < 60)
            {
                Wdlst.Add(data.temper.Value);
            }
            else
            {
                Wdlst.RemoveAt(0);
                Wdlst.Add(data.temper.Value);
            }
            if (Ndlst.Count < 60)
            {
                Ndlst.Add(data.vis.Value);
            }
            else
            {
                Ndlst.RemoveAt(0);
                Ndlst.Add(data.vis.Value);
            }            
            if (data.ppm.HasValue)
            {
                if (ppmlst.Count < 60)
                {
                    ppmlst.Add(data.ppm.Value);
                }
                else
                {
                    ppmlst.RemoveAt(0);
                    ppmlst.Add(data.ppm.Value);
                }

            }            

            if (data.diel.HasValue)
            {
                if (dclst.Count < 60)
                {
                    dclst.Add(data.diel.Value);
                }
                else
                {
                    dclst.RemoveAt(0);
                    dclst.Add(data.diel.Value);
                }
            }

            #region Fe
            if (Fe1lst.Count < 60)
            {
                Fe1lst.Add(data.fe1.Value);
            }
            else
            {
                Fe1lst.RemoveAt(0);
                Fe1lst.Add(data.fe1.Value);
            }
            if (Fe2lst.Count < 60)
            {
                Fe2lst.Add(data.fe2.Value);
            }
            else
            {
                Fe2lst.RemoveAt(0);
                Fe2lst.Add(data.fe2.Value);
            }
            if (Fe3lst.Count < 60)
            {
                Fe3lst.Add(data.fe3.Value);
            }
            else
            {
                Fe3lst.RemoveAt(0);
                Fe3lst.Add(data.fe3.Value);
            }

            if (Fe4lst.Count < 60)
            {
                Fe4lst.Add(data.fe4.Value);
            }
            else
            {
                Fe4lst.RemoveAt(0);
                Fe4lst.Add(data.fe4.Value);
            }
            if (data.fe5.HasValue)
            {
                if (Fe5lst.Count < 60)
                {
                    Fe5lst.Add(data.fe5.Value);
                }
                else
                {
                    Fe5lst.RemoveAt(0);
                    Fe5lst.Add(data.fe5.Value);
                }
            }

            if (data.fe6.HasValue)
            {
                if (Fe6lst.Count < 60)
                {
                    Fe6lst.Add(data.fe6.Value);
                }
                else
                {
                    Fe6lst.RemoveAt(0);
                    Fe6lst.Add(data.fe6.Value);
                }
            }

            if (data.fe7.HasValue)
            {
                if (Fe7lst.Count < 60)
                {
                    Fe7lst.Add(data.fe7.Value);
                }
                else
                {
                    Fe7lst.RemoveAt(0);
                    Fe7lst.Add(data.fe7.Value);
                }
            }

            if (data.fe8.HasValue)
            {
                if (Fe8lst.Count < 60)
                {
                    Fe8lst.Add(data.fe8.Value);
                }
                else
                {
                    Fe8lst.RemoveAt(0);
                    Fe8lst.Add(data.fe8.Value);
                }
            }

            if (data.fe9.HasValue)
            {
                if (Fe9lst.Count < 60)
                {
                    Fe9lst.Add(data.fe9.Value);
                }
                else
                {
                    Fe9lst.RemoveAt(0);
                    Fe9lst.Add(data.fe9.Value);
                }
            }

            if (data.fe10.HasValue)
            {
                if (Fe10lst.Count < 60)
                {
                    Fe10lst.Add(data.fe10.Value);
                }
                else
                {
                    Fe10lst.RemoveAt(0);
                    Fe10lst.Add(data.fe10.Value);
                }
            }

            if (NFe1lst.Count < 60)
            {
                NFe1lst.Add(data.nfe1.Value);
            }
            else
            {
                NFe1lst.RemoveAt(0);
                NFe1lst.Add(data.nfe1.Value);
            }
            if (NFe2lst.Count < 60)
            {
                NFe2lst.Add(data.nfe2.Value);
            }
            else
            {
                NFe2lst.RemoveAt(0);
                NFe2lst.Add(data.nfe2.Value);
            }
            if (NFe3lst.Count < 60)
            {
                NFe3lst.Add(data.nfe3.Value);
            }
            else
            {
                NFe3lst.RemoveAt(0);
                NFe3lst.Add(data.nfe3.Value);
            }
            if (NFe4lst.Count < 60)
            {
                NFe4lst.Add(data.nfe4.Value);
            }
            else
            {
                NFe4lst.RemoveAt(0);
                NFe4lst.Add(data.nfe4.Value);
            }
            #endregion

        }
        private void LoadCurveData(string device_code)
        {            
            try
            {
                if (Wdlst.Count > 0)
                    Wdlst.Clear();
                if (Ndlst.Count > 0)
                    Ndlst.Clear();            
                if (ppmlst.Count > 0)
                    ppmlst.Clear();              
                if (dclst.Count > 0)
                    dclst.Clear();
                if (Fe1lst.Count > 0)
                    Fe1lst.Clear();
                if (Fe2lst.Count > 0)
                    Fe2lst.Clear();
                if (Fe3lst.Count > 0)
                    Fe3lst.Clear();
                if (Fe4lst.Count > 0)
                    Fe4lst.Clear();
                if (Fe5lst.Count > 0)
                    Fe5lst.Clear();
                if (Fe6lst.Count > 0)
                    Fe6lst.Clear();
                if (Fe7lst.Count > 0)
                    Fe7lst.Clear();
                if (Fe8lst.Count > 0)
                    Fe8lst.Clear();
                if (Fe9lst.Count > 0)
                    Fe9lst.Clear();
                if (Fe10lst.Count > 0)
                    Fe10lst.Clear();
                if (NFe1lst.Count > 0)
                    NFe1lst.Clear();
                if (NFe2lst.Count > 0)
                    NFe2lst.Clear();
                if (NFe3lst.Count > 0)
                    NFe3lst.Clear();
                if (NFe4lst.Count > 0)
                    NFe4lst.Clear();
                if (xTime.Count > 0)
                    xTime.Clear();
                DataTable dt = OprUI.GetLastByTopInfo(device_code);
                if (dt != null && dt.Rows.Count > 0)
                {
                    for (int i = dt.Rows.Count - 1; i >= 0; i--)
                    {
                        decimal dmtmp = 0.0m;
                        if (!string.IsNullOrEmpty(dt.Rows[i][1].ToString()))
                            dmtmp = decimal.Parse(dt.Rows[i][1].ToString());
                        else
                            dmtmp = 0.0m;
                        Wdlst.Add(dmtmp);

                        if (!string.IsNullOrEmpty(dt.Rows[i][2].ToString()))
                            dmtmp = decimal.Parse(dt.Rows[i][2].ToString());
                        else
                            dmtmp = 0.0m;
                        Ndlst.Add(dmtmp);

                        if (!string.IsNullOrEmpty(dt.Rows[i][3].ToString()))
                            dmtmp = decimal.Parse(dt.Rows[i][3].ToString());
                        else
                            dmtmp = 0.0m;
                        dclst.Add(dmtmp);

                        if (!string.IsNullOrEmpty(dt.Rows[i][4].ToString()))
                            dmtmp = decimal.Parse(dt.Rows[i][4].ToString());
                        else
                            dmtmp = 0.0m;
                        ppmlst.Add(dmtmp);   

                        decimal num = 0;
                        if (!string.IsNullOrEmpty(dt.Rows[i][5].ToString()))
                            num = int.Parse(dt.Rows[i][5].ToString());
                        else
                            num = 0;
                        Fe1lst.Add(num);
                        if (!string.IsNullOrEmpty(dt.Rows[i][6].ToString()))
                            num = int.Parse(dt.Rows[i][6].ToString());
                        else
                            num = 0;
                        Fe2lst.Add(num);
                        if (!string.IsNullOrEmpty(dt.Rows[i][7].ToString()))
                            num = int.Parse(dt.Rows[i][7].ToString());
                        else
                            num = 0;
                        Fe3lst.Add(num);
                        if (!string.IsNullOrEmpty(dt.Rows[i][8].ToString()))
                            num = int.Parse(dt.Rows[i][8].ToString());
                        else
                            num = 0;
                        Fe4lst.Add(num);
                        if (!string.IsNullOrEmpty(dt.Rows[i][9].ToString()))
                            num = int.Parse(dt.Rows[i][9].ToString());
                        else
                            num = 0;
                        Fe5lst.Add(num);
                        if (!string.IsNullOrEmpty(dt.Rows[i][10].ToString()))
                            num = int.Parse(dt.Rows[i][10].ToString());
                        else
                            num = 0;
                        Fe6lst.Add(num);
                        if (!string.IsNullOrEmpty(dt.Rows[i][11].ToString()))
                            num = int.Parse(dt.Rows[i][11].ToString());
                        else
                            num = 0;
                        Fe7lst.Add(num);
                        if (!string.IsNullOrEmpty(dt.Rows[i][12].ToString()))
                            num = int.Parse(dt.Rows[i][12].ToString());
                        else
                            num = 0;
                        Fe8lst.Add(num);
                        if (!string.IsNullOrEmpty(dt.Rows[i][13].ToString()))
                            num = int.Parse(dt.Rows[i][13].ToString());
                        else
                            num = 0;
                        Fe9lst.Add(num);
                        if (!string.IsNullOrEmpty(dt.Rows[i][14].ToString()))
                            num = int.Parse(dt.Rows[i][14].ToString());
                        else
                            num = 0;
                        Fe10lst.Add(num);

                        if (!string.IsNullOrEmpty(dt.Rows[i][15].ToString()))
                            dmtmp = decimal.Parse(dt.Rows[i][15].ToString());
                        else
                            dmtmp = 0.0m;
                        NFe1lst.Add(dmtmp);
                        if (!string.IsNullOrEmpty(dt.Rows[i][16].ToString()))
                            dmtmp = decimal.Parse(dt.Rows[i][16].ToString());
                        else
                            dmtmp = 0.0m;
                        NFe2lst.Add(dmtmp);
                        if (!string.IsNullOrEmpty(dt.Rows[i][17].ToString()))
                            dmtmp = decimal.Parse(dt.Rows[i][17].ToString());
                        else
                            dmtmp = 0.0m;
                        NFe3lst.Add(dmtmp);
                        if (!string.IsNullOrEmpty(dt.Rows[i][18].ToString()))
                            dmtmp = decimal.Parse(dt.Rows[i][18].ToString());
                        else
                            dmtmp = 0.0m;
                        NFe4lst.Add(dmtmp);

                        xTime.Add(((DateTime)dt.Rows[i][0]).ToString("HH:mm"));
                    }
                }
                else
                {
                    DateTime time = DateTime.Now.AddMinutes(-60);
                    for (int i = 0; i < 60; i++)
                    {
                        Wdlst.Add(0.0m);
                        Ndlst.Add(0.0m);
                        ppmlst.Add(0.0m);
                        dclst.Add(0.0m);
                        Fe1lst.Add(0);
                        Fe2lst.Add(0);
                        Fe3lst.Add(0);
                        Fe4lst.Add(0);
                        Fe5lst.Add(0);
                        Fe6lst.Add(0);
                        Fe7lst.Add(0);
                        Fe8lst.Add(0);
                        Fe9lst.Add(0);
                        Fe10lst.Add(0);
                        NFe1lst.Add(0.0m);
                        NFe2lst.Add(0.0m);
                        NFe3lst.Add(0.0m);
                        NFe4lst.Add(0.0m);
                        xTime.Add(time.AddMinutes(i).ToString("HH:mm"));
                    }
                }
                ShowChartData();
            }
            catch (Exception ex)
            {
                lLogWrite.WriteLog("数据库连接失败,请重新配置");
            }
            finally
            {
                //lLogWrite.WriteLog("###数据初始化###");
            }
        }
        #endregion    
        #region
        /// <summary>
        /// 设备及终端信息
        /// </summary>
        /// <param name="devicelist"></param>
        private delegate void ShowDeviceInformationByDelegate(Devicelist devicelist);
        private void ShowDeviceInformateion(Devicelist vo)
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new ShowDeviceInformationByDelegate(ShowDeviceInformateion), vo);
            }
            else
            {
                this.labelDvName.Text = vo.devName;
                if (!string.IsNullOrEmpty(vo.devPos))
                    this.labelDvPosition.Text = vo.devPos;
                if (!string.IsNullOrEmpty(vo.sensorName))
                    this.labelSensorCode.Text = vo.sensorName;
                if (!string.IsNullOrEmpty(vo.oilName))
                    this.labelDvOil.Text = vo.oilName;
                TimeSpan timeSpan = DateTime.Now - vo.devInstallTime;
                this.labelDvTime.Text = timeSpan.Days.ToString() + "天";
                timeSpan = DateTime.Now - vo.oilFillTime;
                labelOilTime.Text = timeSpan.Days.ToString() + "天";
                if (vo.online_status)
                {
                    labelDvStatus.Text = "开机";
                    labelSensorStatus.Text = "在线";
                }
                else
                {
                    labelDvStatus.Text = "停机";
                    labelSensorStatus.Text = "在线";

                }
            }

        }
        private delegate void ShowSensorInformationDelegate(sensordatas sensordatas);
        private void ShowSensorInformation(sensordatas sensordatas)
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new ShowSensorInformationDelegate(ShowSensorInformation), new object[] { sensordatas });
            }
            else
            {
                if (sensordatas != null)
                {
                    if (sensordatas.temper.HasValue)
                        btnTemper.Text = sensordatas.temper.ToString();
                    else
                        btnTemper.Text = "-";
                    if(sensordatas.vis.HasValue)
                        btnCst.Text= sensordatas.vis.ToString();
                    else
                        btnCst.Text = "-";
                    if(sensordatas.dens.HasValue)
                        btnDens.Text = sensordatas.dens.ToString();
                    else
                        btnDens.Text = "-";
                    if(sensordatas.diel.HasValue)
                        btnDiel.Text = sensordatas.diel.ToString();
                    else
                        btnDiel.Text = "-";
                    if(sensordatas.ppm.HasValue)
                        button5.Text = sensordatas.ppm.ToString();
                    else
                        button5.Text= "-";
                    if(sensordatas.aw.HasValue)
                        btnAw.Text=sensordatas.aw.ToString();
                    else
                        btnAw.Text= "-";
                    if(sensordatas.mo.HasValue)
                        btnMo.Text= sensordatas.mo.ToString();
                    else
                        btnMo.Text= "-";
                    if(sensordatas.fe1.HasValue)
                        btnFe1.Text= sensordatas.fe1.ToString();
                    else
                        btnFe1.Text= "-";
                    if(sensordatas.fe2.HasValue)
                        btnFe2.Text= sensordatas.fe2.ToString();
                    else
                        btnFe2.Text= "-";
                    if(sensordatas.fe3.HasValue)
                        btnFe3.Text= sensordatas.fe3.ToString();
                    else
                        btnFe3.Text= "-";
                    if(sensordatas.fe4.HasValue)
                        btnFe4.Text= sensordatas.fe4.ToString();
                    else
                        btnFe4.Text= "-";   
                    if(sensordatas.fe5.HasValue)
                        btnFe5.Text= sensordatas.fe5.ToString();
                    else
                        btnFe5.Text= "-";
                    if(sensordatas.fe6.HasValue)
                        btnFe6.Text= sensordatas.fe6.ToString();
                    else
                        btnFe6.Text= "-";
                    if(sensordatas.fe7.HasValue)
                        btnFe7.Text= sensordatas.fe7.ToString();
                    else
                        btnFe7.Text= "-";
                    if(sensordatas.fe8.HasValue)
                        btnFe8.Text= sensordatas.fe8.ToString();
                    else
                        btnFe8.Text= "-";
                    if(sensordatas.fe9.HasValue)
                        btnFe9.Text= sensordatas.fe9.ToString();
                    else
                        btnFe9.Text= "-";
                    if(sensordatas.fe10.HasValue)
                        btnFe10.Text= sensordatas.fe10.ToString();  
                    else
                        btnFe10.Text= "-";  
                    if(sensordatas.nfe1.HasValue)
                        btnNFe1.Text= sensordatas.nfe1.ToString();
                    else
                        btnNFe1.Text = "-";
                    if(sensordatas.nfe2.HasValue)
                        btnNFe2.Text= sensordatas.nfe2.ToString();
                    else
                        btnNFe2.Text= "-";
                    if(sensordatas.nfe3.HasValue)
                        button12.Text = sensordatas.nfe3.ToString(); 
                    else
                        button12.Text= "-";  
                    if(sensordatas.nfe4.HasValue)
                        button14.Text= sensordatas.nfe4.ToString();
                    else
                        button14.Text= "-";
                   
                }
                else
                {
                    btnTemper.Text= "-";
                    btnCst.Text= "-";
                    btnAw.Text= "-";
                    btnDens.Text= "-";
                    btnDiel.Text= "-";
                    button5.Text= "-";
                    btnMo.Text= "-";
                    btnFe1.Text= "-";
                    btnFe2.Text= "-";
                    btnFe3.Text= "-";
                    btnFe4.Text= "-";
                    btnFe5.Text= "-";
                    btnFe6.Text= "-";
                    btnFe7.Text= "-";
                    btnFe8.Text= "-";
                    btnFe9.Text= "-";
                    btnFe10.Text= "-";
                    btnNFe1.Text= "-";
                    btnNFe2.Text= "-";
                    button12.Text= "-";
                    button14.Text= "-";                    
                }
                
            }
        }
           
        #endregion
        private void MonitorFrm_Load(object sender, EventArgs e)
        {
            labelDateTime.Text = DateTime.Now.ToString("时间：yyyy-MM-dd HH:mm:ss");
            #region 尺寸比例
            this.WindowState = FormWindowState.Maximized;
            this.panelLeft.Width = this.Width /5;
            this.panelRight.Width = this.Width /5;
            int CalHeight = this.Height - this.panelMenu.Height - this.panelReserve.Height;
            this.groupBoxLeftTop.Height = CalHeight / 3;
            this.groupBoxLeftMid.Height = CalHeight / 3;
            this.groupBoxRightTop.Height = CalHeight / 3;
            this.groupBoxRightMiddle.Height = CalHeight / 3;
            this.groupBoxDatas.Height = this.groupBoxleftButtom.Height;
            this.groupBoxFe.Height = this.groupBoxLeftMid.Height;
            #endregion          
            initAlarmChart();          
            //initOiChart();
            //initVisMoChart();
            //initFeChart();
        } 

        #region 初始化图表  
        /// <summary>
        /// 预警图表初始化
        /// </summary>
        private void initAlarmChart()
        {
            #region 单曲线
            //carChartAlarm.Series.Clear();
            //List<string> lables = new List<string> { "温度", "粘度", "密度", "水分", "Fe", "NFe" };
            //Axis axis = new Axis
            //{
            //    Title = "名称",
            //    Labels = lables
            //};
            //ChartValues<double> vales = new ChartValues<double>();
            //for (int i = 0; i < lables.Count; i++)
            //{
            //    vales.Add(30 + i);
            //}
            //carChartAlarm.Series = new SeriesCollection
            //{
            //    new LineSeries
            //    {
            //        Title="运行数",
            //        Values=vales,
            //        Fill=new SolidColorBrush(Colors.Pink),
            //        Stroke=new SolidColorBrush(Colors.Azure),
            //        LineSmoothness=1

            //    }
            //};
            //carChartAlarm.AxisX.Add(axis);
            //carChartAlarm.AxisY.Add(new Axis
            //{
            //    Title = "数量",
            //    LabelFormatter = value => value.ToString()
            //});
            #endregion
            carChartAlarm.Series.Clear();
            List<string> titles = new List<string> { "粘度", "水分", "铁磁" };
            List<ChartValues<double>> _values = new List<ChartValues<double>> 
            { 
                new ChartValues<double> { 6, 5, 3 },
                new ChartValues<double> { 5, 8, 2},
                new ChartValues<double> { 3, 4, 1}
            };
            List<double> vis_datas = new List<double> { 6, 5, 3 };
            List<double> mo_datas = new List<double> { 3, 8, 2 };
            List<double> fe_datas = new List<double> {5,2,6 };
            List<string> _labels = new List<string>();
            SeriesCollection seriesViews = new SeriesCollection();
            for (int i = 0; i < titles.Count; i++)
            {
                LineSeries lineseries = new LineSeries();
                lineseries.DataLabels = true;
                lineseries.Title = titles[i];
                lineseries.Values = _values[i];
                lineseries.LineSmoothness = 1;
                lineseries.LabelPoint = (point => point.Y + "次");
                seriesViews.Add(lineseries);     
                _labels.Add(DateTime.Now.AddDays(i-3).ToString("yyyy-MM-dd"));
            }
            carChartAlarm.Series = seriesViews;
            Axis axis = new Axis
            {
                //Title = "名称",
                Labels = _labels

            };
            carChartAlarm.AxisX.Add(axis);
            carChartAlarm.AxisY.Add(new Axis
            {
                Title = "预警次数",
                LabelFormatter = value => value.ToString()
            });      
        }      
        /// <summary>
        /// 油品图表初始化
        /// </summary>
        private void initOiChart()
        {
            SeriesCollection seriesCollection = new SeriesCollection();
            LineSeries lineSeries = new LineSeries();
            List<string> labels = new List<string> { "320#", "220#", "150#","46#" };
            ChartValues<double> values = new ChartValues<double> { 5, 6, 10, 2 };
            lineSeries.Title = "油品";
            lineSeries.Values = values;
            lineSeries.DataLabels = true;
            Axis axis = new Axis();            
            axis.LabelFormatter = value => value.ToString();
            axis.Labels = labels;
            axis.Separator = new Separator() {IsEnabled=false };
            seriesCollection.Add(lineSeries);
            carChartOils.Series.Clear();
            carChartOils.Series.Add(lineSeries);
            carChartOils.AxisX.Add(axis);     
            Axis axis2 = new Axis();
            axis2.Title = "油品统计";
            axis2.Separator.IsEnabled = false;
            axis2.LabelFormatter = value => value.ToString() + "个";
            carChartOils.AxisY.Add(axis2);

        }
        /// <summary>
        /// 油品状态初始化
        /// </summary>
        private void initParasChart()
        {
            angularGauge1.Value = 65;
            angularGauge1.FromValue = 0;
            angularGauge1.ToValue = 100;
            angularGauge1.TicksForeground = Brushes.White;
            angularGauge1.Base.Foreground = Brushes.White;
            angularGauge1.Base.FontWeight = FontWeights.Bold;
            angularGauge1.Base.FontSize = 16;
            angularGauge1.SectionsInnerRadius = 0.5;
            angularGauge1.Sections.Add(new AngularSection
            {
                FromValue =0,
                ToValue =70,
                //Fill=new SolidColorBrush(System.Windows.Media.Color.FromRgb(247, 166, 37))
                Fill = new SolidColorBrush(Colors.Green)
            });
            angularGauge1.Sections.Add(new AngularSection
            {
                FromValue = 70,
                ToValue = 85,
                //Fill=new SolidColorBrush(System.Windows.Media.Color.FromRgb(247, 166, 37))
                Fill= new SolidColorBrush(Colors.Yellow)
            });            
            angularGauge1.Sections.Add(new AngularSection
            {
                FromValue = 85,
                ToValue = 100,
                //Fill = new SolidColorBrush(System.Windows.Media.Color.FromRgb(247, 57, 57))
                Fill=new SolidColorBrush(Colors.Red)
            });
            angularGauge1.Refresh();
        }
        private void initVisMoChart()
        {
            carChartVisTemper.Series.Clear();
            List<string> titles = new List<string> { "粘度", "水分", "温度" };
            List<ChartValues<double>> _values = new List<ChartValues<double>>
            {
                new ChartValues<double> { 315.6, 318.5, 319.3, 314.5, 312.3, 318.5, 319.3 },
                new ChartValues<double> { 105, 108, 102, 108, 102, 108, 102},
                new ChartValues<double> { 39.3, 39.4, 39.1, 38.0, 39.1, 40.4, 40.1 }
            };
            List<double> vis_datas = new List<double> { 6, 5, 3 };
            List<double> mo_datas = new List<double> { 3, 8, 2 };
            List<double> fe_datas = new List<double> { 5, 2, 6 };
            List<string> _labels = new List<string>();
            SeriesCollection seriesViews = new SeriesCollection();
            for (int i = 0; i < titles.Count; i++)
            {
                LineSeries lineseries = new LineSeries();
                lineseries.DataLabels = true;
                lineseries.Title = titles[i];
                lineseries.Values = _values[i];
                lineseries.LineSmoothness = 1;
                lineseries.LabelPoint = (point => point.Y.ToString());
                seriesViews.Add(lineseries);
               
            }
            for(int i=0;i<7;i++)
            {
                _labels.Add(DateTime.Now.AddMinutes(i - 10).ToString("HH:mm"));
            }
            carChartVisTemper.Series = seriesViews;
            Axis axis = new Axis
            {
                Labels = _labels
            };
            carChartVisTemper.AxisX.Add(axis);
            carChartVisTemper.AxisY.Add(new Axis
            {
                Title = "理化趋势图",
                LabelFormatter = value => value.ToString()
            });
        }
        private void initFeChart()
        {
            carChartFe.Series.Clear();
            List<string> titles = new List<string> { "Fe1", "Fe2", "Fe3" };
            List<ChartValues<double>> _values = new List<ChartValues<double>>
            {
                new ChartValues<double> { 100, 99, 95, 101,79, 82, 79 },
                new ChartValues<double> { 80, 81, 79, 88, 56, 62, 60},
                new ChartValues<double> { 60, 59, 55, 62, 52, 56, 51 }
            };
            List<double> vis_datas = new List<double> { 6, 5, 3 };
            List<double> mo_datas = new List<double> { 3, 8, 2 };
            List<double> fe_datas = new List<double> { 5, 2, 6 };
            List<string> _labels = new List<string>();
            SeriesCollection seriesViews = new SeriesCollection();
            for (int i = 0; i < titles.Count; i++)
            {
                LineSeries lineseries = new LineSeries();
                lineseries.DataLabels = true;
                lineseries.Title = titles[i];
                lineseries.Values = _values[i];
                lineseries.LineSmoothness = 1;
                lineseries.LabelPoint = (point => point.Y.ToString());
                seriesViews.Add(lineseries);

            }
            for (int i = 0; i < 7; i++)
            {
                _labels.Add(DateTime.Now.AddMinutes(i - 10).ToString("HH:mm"));
            }
            carChartFe.Series = seriesViews;
            Axis axis = new Axis
            {
                //Title = "名称",
                Labels = _labels

            };
            carChartFe.AxisX.Add(axis);
            carChartFe.AxisY.Add(new Axis
            {
                Title = "磨粒趋势",
                LabelFormatter = value => value.ToString()
            });
        }
        #endregion

        #region 实时监控

        private bool m_bInitSDK = false;
        private uint iLastErr = 0;
        private Int32 m_lUserID = -1;
        private Int32 m_lRealHandle = -1;
        private string str1;
        private string str2;
        private Int32 i = 0;
        private Int32 m_lTree = 0;
        private string str;
        private long iSelIndex = 0;
        private uint dwAChanTotalNum = 0;
        private uint dwDChanTotalNum = 0;
        private Int32 m_lPort = -1;
        private IntPtr m_ptrRealHandle;
        private int[] iIPDevID = new int[96];
        private int[] iChannelNum = new int[96];
        private ComboBox comboBoxView = new ComboBox();
        private ListView listViewIPChannel = new ListView();

        private CHCNetSDK.REALDATACALLBACK RealData = null;
        public CHCNetSDK.NET_DVR_DEVICEINFO_V30 DeviceInfo;
        public CHCNetSDK.NET_DVR_IPPARACFG_V40 m_struIpParaCfgV40;
        public CHCNetSDK.NET_DVR_STREAM_MODE m_struStreamMode;
        public CHCNetSDK.NET_DVR_IPCHANINFO m_struChanInfo;
        public CHCNetSDK.NET_DVR_PU_STREAM_URL m_struStreamURL;
        public CHCNetSDK.NET_DVR_IPCHANINFO_V40 m_struChanInfoV40;
        private PlayCtrl.DECCBFUN m_fDisplayFun = null;
        public delegate void MyDebugInfo(string str);

        private string CameraDeviceIp = "";
        private string CameraDevicePort = "";
        private string CameraDeviceUser = "admin";
        private string CameraDevicePassword = "Hf123456";

        public void CameraDeviceInit()
        {
            DevicedConfig();
            m_bInitSDK = CHCNetSDK.NET_DVR_Init();
            if (m_bInitSDK == false)
            {
                return;
            }
            else
            {
                //保存SDK日志 To save the SDK log
                //CHCNetSDK.NET_DVR_SetLogToFile(3, "C:\\SdkLog\\", true);

                comboBoxView.SelectedIndex = 0;

                for (int i = 0; i < 64; i++)
                {
                    iIPDevID[i] = -1;
                    iChannelNum[i] = -1;
                }
            }
            LoginIn();
            Preview_Open();
        }

        #region 工具函数
        private void DevicedConfig()
        {
            INIFile ini = new INIFile("config.ini");
            string value = ini.IniReadValue("Camera", "DeviceIp");
            CameraDeviceIp = value;
            value = ini.IniReadValue("Camera", "DevicePort");
            CameraDevicePort = value;
            comboBoxView.Items.Add("Direct:直接预览");
            comboBoxView.Items.Add("Callback:回调解码");
        }

        public void DebugInfo(string str)
        {
            if (str.Length > 0)
            {
                str += "\n";
                //TextBoxInfo.AppendText(str);
            }
        }

        public void InfoIPChannel()
        {
            uint dwSize = (uint)Marshal.SizeOf(m_struIpParaCfgV40);

            IntPtr ptrIpParaCfgV40 = Marshal.AllocHGlobal((Int32)dwSize);
            Marshal.StructureToPtr(m_struIpParaCfgV40, ptrIpParaCfgV40, false);

            uint dwReturn = 0;
            int iGroupNo = 0;  //该Demo仅获取第一组64个通道，如果设备IP通道大于64路，需要按组号0~i多次调用NET_DVR_GET_IPPARACFG_V40获取

            if (!CHCNetSDK.NET_DVR_GetDVRConfig(m_lUserID, CHCNetSDK.NET_DVR_GET_IPPARACFG_V40, iGroupNo, ptrIpParaCfgV40, dwSize, ref dwReturn))
            {
                iLastErr = CHCNetSDK.NET_DVR_GetLastError();
                str = "NET_DVR_GET_IPPARACFG_V40 failed, error code= " + iLastErr;
                //获取IP资源配置信息失败，输出错误号 Failed to get configuration of IP channels and output the error code
                DebugInfo(str);
            }
            else
            {
                DebugInfo("NET_DVR_GET_IPPARACFG_V40 succ!");

                m_struIpParaCfgV40 = (CHCNetSDK.NET_DVR_IPPARACFG_V40)Marshal.PtrToStructure(ptrIpParaCfgV40, typeof(CHCNetSDK.NET_DVR_IPPARACFG_V40));

                for (i = 0; i < dwAChanTotalNum; i++)
                {
                    ListAnalogChannel(i + 1, m_struIpParaCfgV40.byAnalogChanEnable[i]);
                    iChannelNum[i] = i + (int)DeviceInfo.byStartChan;
                }

                byte byStreamType = 0;
                uint iDChanNum = 64;

                if (dwDChanTotalNum < 64)
                {
                    iDChanNum = dwDChanTotalNum; //如果设备IP通道小于64路，按实际路数获取
                }

                for (i = 0; i < iDChanNum; i++)
                {
                    iChannelNum[i + dwAChanTotalNum] = i + (int)m_struIpParaCfgV40.dwStartDChan;
                    byStreamType = m_struIpParaCfgV40.struStreamMode[i].byGetStreamType;

                    dwSize = (uint)Marshal.SizeOf(m_struIpParaCfgV40.struStreamMode[i].uGetStream);
                    switch (byStreamType)
                    {
                        //目前NVR仅支持直接从设备取流 NVR supports only the mode: get stream from device directly
                        case 0:
                            IntPtr ptrChanInfo = Marshal.AllocHGlobal((Int32)dwSize);
                            Marshal.StructureToPtr(m_struIpParaCfgV40.struStreamMode[i].uGetStream, ptrChanInfo, false);
                            m_struChanInfo = (CHCNetSDK.NET_DVR_IPCHANINFO)Marshal.PtrToStructure(ptrChanInfo, typeof(CHCNetSDK.NET_DVR_IPCHANINFO));

                            //列出IP通道 List the IP channel
                            ListIPChannel(i + 1, m_struChanInfo.byEnable, m_struChanInfo.byIPID);
                            iIPDevID[i] = m_struChanInfo.byIPID + m_struChanInfo.byIPIDHigh * 256 - iGroupNo * 64 - 1;

                            Marshal.FreeHGlobal(ptrChanInfo);
                            break;
                        case 4:
                            IntPtr ptrStreamURL = Marshal.AllocHGlobal((Int32)dwSize);
                            Marshal.StructureToPtr(m_struIpParaCfgV40.struStreamMode[i].uGetStream, ptrStreamURL, false);
                            m_struStreamURL = (CHCNetSDK.NET_DVR_PU_STREAM_URL)Marshal.PtrToStructure(ptrStreamURL, typeof(CHCNetSDK.NET_DVR_PU_STREAM_URL));

                            //列出IP通道 List the IP channel
                            ListIPChannel(i + 1, m_struStreamURL.byEnable, m_struStreamURL.wIPID);
                            iIPDevID[i] = m_struStreamURL.wIPID - iGroupNo * 64 - 1;

                            Marshal.FreeHGlobal(ptrStreamURL);
                            break;
                        case 6:
                            IntPtr ptrChanInfoV40 = Marshal.AllocHGlobal((Int32)dwSize);
                            Marshal.StructureToPtr(m_struIpParaCfgV40.struStreamMode[i].uGetStream, ptrChanInfoV40, false);
                            m_struChanInfoV40 = (CHCNetSDK.NET_DVR_IPCHANINFO_V40)Marshal.PtrToStructure(ptrChanInfoV40, typeof(CHCNetSDK.NET_DVR_IPCHANINFO_V40));

                            //列出IP通道 List the IP channel
                            ListIPChannel(i + 1, m_struChanInfoV40.byEnable, m_struChanInfoV40.wIPID);
                            iIPDevID[i] = m_struChanInfoV40.wIPID - iGroupNo * 64 - 1;

                            Marshal.FreeHGlobal(ptrChanInfoV40);
                            break;
                        default:
                            break;
                    }
                }
            }
            Marshal.FreeHGlobal(ptrIpParaCfgV40);
        }

        public void ListIPChannel(Int32 iChanNo, byte byOnline, int byIPID)
        {
            str1 = String.Format("IPCamera {0}", iChanNo);
            m_lTree++;

            if (byIPID == 0)
            {
                str2 = "X"; //通道空闲，没有添加前端设备 the channel is idle                  
            }
            else
            {
                if (byOnline == 0)
                {
                    str2 = "offline"; //通道不在线 the channel is off-line
                }
                else
                    str2 = "online"; //通道在线 The channel is on-line
            }

            listViewIPChannel.Items.Add(new ListViewItem(new string[] { str1, str2 }));//将通道添加到列表中 add the channel to the list
        }

        public void ListAnalogChannel(Int32 iChanNo, byte byEnable)
        {
            str1 = String.Format("Camera {0}", iChanNo);
            m_lTree++;

            if (byEnable == 0)
            {
                str2 = "Disabled"; //通道已被禁用 This channel has been disabled               
            }
            else
            {
                str2 = "Enabled"; //通道处于启用状态 This channel has been enabled
            }

            listViewIPChannel.Items.Add(new ListViewItem(new string[] { str1, str2 }));//将通道添加到列表中 add the channel to the list
        }

        private void LoginIn()
        {
            if (m_lUserID < 0)
            {
                string DVRIPAddress = CameraDeviceIp; //设备IP地址或者域名 Device IP
                Int16 DVRPortNumber = Int16.Parse(CameraDevicePort);//设备服务端口号 Device Port
                string DVRUserName = CameraDeviceUser;//设备登录用户名 User name to login
                string DVRPassword = CameraDevicePassword;//设备登录密码 Password to login

                //登录设备 Login the device
                m_lUserID = CHCNetSDK.NET_DVR_Login_V30(DVRIPAddress, DVRPortNumber, DVRUserName, DVRPassword, ref DeviceInfo);
                if (m_lUserID < 0)
                {
                    iLastErr = CHCNetSDK.NET_DVR_GetLastError();
                    str = "NET_DVR_Login_V30 failed, error code= " + iLastErr; //登录失败，输出错误号 Failed to login and output the error code
                    DebugInfo(str);
                    return;
                }
                else
                {
                    //登录成功
                    DebugInfo("NET_DVR_Login_V30 succ!");

                    dwAChanTotalNum = (uint)DeviceInfo.byChanNum;
                    dwDChanTotalNum = (uint)DeviceInfo.byIPChanNum + 256 * (uint)DeviceInfo.byHighDChanNum;
                    if (dwDChanTotalNum > 0)
                    {
                        InfoIPChannel();
                    }
                    else
                    {
                        for (i = 0; i < dwAChanTotalNum; i++)
                        {
                            ListAnalogChannel(i + 1, 1);
                            iChannelNum[i] = i + (int)DeviceInfo.byStartChan;
                        }

                        comboBoxView.SelectedItem = 1;
                    }
                }
            }
        }

        private void LoginOut()
        {
            if (m_lUserID >= 0)
            {
                //注销登录 Logout the device
                if (m_lRealHandle >= 0)
                {
                    DebugInfo("Please stop live view firstly"); //登出前先停止预览 Stop live view before logout
                    return;
                }

                if (!CHCNetSDK.NET_DVR_Logout(m_lUserID))
                {
                    iLastErr = CHCNetSDK.NET_DVR_GetLastError();
                    str = "NET_DVR_Logout failed, error code= " + iLastErr;
                    DebugInfo(str);
                    return;
                }
                DebugInfo("NET_DVR_Logout succ!");
                listViewIPChannel.Items.Clear();//清空通道列表 Clean up the channel list
                m_lUserID = -1;
            }
            return;
        }

        private void Preview_Open()
        {
            if (m_lUserID < 0)
            {
                return;
            }

            if (m_lRealHandle < 0)
            {
                CHCNetSDK.NET_DVR_PREVIEWINFO lpPreviewInfo = new CHCNetSDK.NET_DVR_PREVIEWINFO();
                lpPreviewInfo.hPlayWnd = RealPlayWnd.Handle;//预览窗口 live view window
                lpPreviewInfo.lChannel = iChannelNum[(int)iSelIndex];//预览的设备通道 the device channel number
                lpPreviewInfo.dwStreamType = 0;//码流类型：0-主码流，1-子码流，2-码流3，3-码流4，以此类推
                lpPreviewInfo.dwLinkMode = 0;//连接方式：0- TCP方式，1- UDP方式，2- 多播方式，3- RTP方式，4-RTP/RTSP，5-RSTP/HTTP 
                lpPreviewInfo.bBlocked = true; //0- 非阻塞取流，1- 阻塞取流
                lpPreviewInfo.dwDisplayBufNum = 15; //播放库显示缓冲区最大帧数

                IntPtr pUser = IntPtr.Zero;//用户数据 user data 

                if (comboBoxView.SelectedIndex == 0)
                {
                    //打开预览 Start live view 
                    m_lRealHandle = CHCNetSDK.NET_DVR_RealPlay_V40(m_lUserID, ref lpPreviewInfo, null/*RealData*/, pUser);
                }
                else
                {
                    lpPreviewInfo.hPlayWnd = IntPtr.Zero;//预览窗口 live view window
                    m_ptrRealHandle = RealPlayWnd.Handle;
                    RealData = new CHCNetSDK.REALDATACALLBACK(RealDataCallBack);//预览实时流回调函数 real-time stream callback function 
                    m_lRealHandle = CHCNetSDK.NET_DVR_RealPlay_V40(m_lUserID, ref lpPreviewInfo, RealData, pUser);
                }

                if (m_lRealHandle < 0)
                {
                    iLastErr = CHCNetSDK.NET_DVR_GetLastError();
                    str = "NET_DVR_RealPlay_V40 failed, error code= " + iLastErr; //预览失败，输出错误号 failed to start live view, and output the error code.
                    DebugInfo(str);
                    return;
                }
                else
                {
                    //预览成功
                    DebugInfo("NET_DVR_RealPlay_V40 succ!");
                }
            }
        }

        private void Preview_Close()
        {
            if (m_lUserID < 0)
            {
                return;
            }

            if (m_lRealHandle >= 0)
            {
                //停止预览 Stop live view 
                if (!CHCNetSDK.NET_DVR_StopRealPlay(m_lRealHandle))
                {
                    iLastErr = CHCNetSDK.NET_DVR_GetLastError();
                    str = "NET_DVR_StopRealPlay failed, error code= " + iLastErr;
                    DebugInfo(str);
                    return;
                }

                if ((comboBoxView.SelectedIndex == 1) && (m_lPort >= 0))
                {
                    if (!PlayCtrl.PlayM4_Stop(m_lPort))
                    {
                        iLastErr = PlayCtrl.PlayM4_GetLastError(m_lPort);
                        str = "PlayM4_Stop failed, error code= " + iLastErr;
                        DebugInfo(str);
                    }
                    if (!PlayCtrl.PlayM4_CloseStream(m_lPort))
                    {
                        iLastErr = PlayCtrl.PlayM4_GetLastError(m_lPort);
                        str = "PlayM4_CloseStream failed, error code= " + iLastErr;
                        DebugInfo(str);
                    }
                    if (!PlayCtrl.PlayM4_FreePort(m_lPort))
                    {
                        iLastErr = PlayCtrl.PlayM4_GetLastError(m_lPort);
                        str = "PlayM4_FreePort failed, error code= " + iLastErr;
                        DebugInfo(str);
                    }
                    m_lPort = -1;
                }

                DebugInfo("NET_DVR_StopRealPlay succ!");
                m_lRealHandle = -1;
                RealPlayWnd.Invalidate();//刷新窗口 refresh the window
            }
        }
        #endregion

        #region 图像处理回调函数
        //解码回调函数
        private void DecCallbackFUN(int nPort, IntPtr pBuf, int nSize, ref PlayCtrl.FRAME_INFO pFrameInfo, int nReserved1, int nReserved2)
        {
            // 将pBuf解码后视频输入写入文件中（解码后YUV数据量极大，尤其是高清码流，不建议在回调函数中处理）
            if (pFrameInfo.nType == 3) //#define T_YV12	3
            {
                //    FileStream fs = null;
                //    BinaryWriter bw = null;
                //    try
                //    {
                //        fs = new FileStream("DecodedVideo.yuv", FileMode.Append);
                //        bw = new BinaryWriter(fs);
                //        byte[] byteBuf = new byte[nSize];
                //        Marshal.Copy(pBuf, byteBuf, 0, nSize);
                //        bw.Write(byteBuf);
                //        bw.Flush();
                //    }
                //    catch (System.Exception ex)
                //    {
                //        MessageBox.Show(ex.ToString());
                //    }
                //    finally
                //    {
                //        bw.Close();
                //        fs.Close();
                //    }
            }
        }

        public void RealDataCallBack(Int32 lRealHandle, UInt32 dwDataType, IntPtr pBuffer, UInt32 dwBufSize, IntPtr pUser)
        {
            //下面数据处理建议使用委托的方式
            MyDebugInfo AlarmInfo = new MyDebugInfo(DebugInfo);
            switch (dwDataType)
            {
                case CHCNetSDK.NET_DVR_SYSHEAD:     // sys head
                    if (dwBufSize > 0)
                    {
                        if (m_lPort >= 0)
                        {
                            return; //同一路码流不需要多次调用开流接口
                        }

                        //获取播放句柄 Get the port to play
                        if (!PlayCtrl.PlayM4_GetPort(ref m_lPort))
                        {
                            iLastErr = PlayCtrl.PlayM4_GetLastError(m_lPort);
                            str = "PlayM4_GetPort failed, error code= " + iLastErr;
                            this.BeginInvoke(AlarmInfo, str);
                            break;
                        }

                        //设置流播放模式 Set the stream mode: real-time stream mode
                        if (!PlayCtrl.PlayM4_SetStreamOpenMode(m_lPort, PlayCtrl.STREAME_REALTIME))
                        {
                            iLastErr = PlayCtrl.PlayM4_GetLastError(m_lPort);
                            str = "Set STREAME_REALTIME mode failed, error code= " + iLastErr;
                            this.BeginInvoke(AlarmInfo, str);
                        }

                        //打开码流，送入头数据 Open stream
                        if (!PlayCtrl.PlayM4_OpenStream(m_lPort, pBuffer, dwBufSize, 2 * 1024 * 1024))
                        {
                            iLastErr = PlayCtrl.PlayM4_GetLastError(m_lPort);
                            str = "PlayM4_OpenStream failed, error code= " + iLastErr;
                            this.BeginInvoke(AlarmInfo, str);
                            break;
                        }


                        //设置显示缓冲区个数 Set the display buffer number
                        if (!PlayCtrl.PlayM4_SetDisplayBuf(m_lPort, 15))
                        {
                            iLastErr = PlayCtrl.PlayM4_GetLastError(m_lPort);
                            str = "PlayM4_SetDisplayBuf failed, error code= " + iLastErr;
                            this.BeginInvoke(AlarmInfo, str);
                        }

                        //设置显示模式 Set the display mode
                        if (!PlayCtrl.PlayM4_SetOverlayMode(m_lPort, 0, 0/* COLORREF(0)*/)) //play off screen 
                        {
                            iLastErr = PlayCtrl.PlayM4_GetLastError(m_lPort);
                            str = "PlayM4_SetOverlayMode failed, error code= " + iLastErr;
                            this.BeginInvoke(AlarmInfo, str);
                        }

                        //设置解码回调函数，获取解码后音视频原始数据 Set callback function of decoded data
                        m_fDisplayFun = new PlayCtrl.DECCBFUN(DecCallbackFUN);
                        if (!PlayCtrl.PlayM4_SetDecCallBackEx(m_lPort, m_fDisplayFun, IntPtr.Zero, 0))
                        {
                            this.BeginInvoke(AlarmInfo, "PlayM4_SetDisplayCallBack fail");
                        }

                        //开始解码 Start to play                       
                        if (!PlayCtrl.PlayM4_Play(m_lPort, m_ptrRealHandle))
                        {
                            iLastErr = PlayCtrl.PlayM4_GetLastError(m_lPort);
                            str = "PlayM4_Play failed, error code= " + iLastErr;
                            this.BeginInvoke(AlarmInfo, str);
                            break;
                        }
                    }
                    break;
                case CHCNetSDK.NET_DVR_STREAMDATA:     // video stream data
                    if (dwBufSize > 0 && m_lPort != -1)
                    {
                        for (int i = 0; i < 999; i++)
                        {
                            //送入码流数据进行解码 Input the stream data to decode
                            if (!PlayCtrl.PlayM4_InputData(m_lPort, pBuffer, dwBufSize))
                            {
                                iLastErr = PlayCtrl.PlayM4_GetLastError(m_lPort);
                                str = "PlayM4_InputData failed, error code= " + iLastErr;
                                Thread.Sleep(2);
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                    break;
                default:
                    if (dwBufSize > 0 && m_lPort != -1)
                    {
                        //送入其他数据 Input the other data
                        for (int i = 0; i < 999; i++)
                        {
                            if (!PlayCtrl.PlayM4_InputData(m_lPort, pBuffer, dwBufSize))
                            {
                                iLastErr = PlayCtrl.PlayM4_GetLastError(m_lPort);
                                str = "PlayM4_InputData failed, error code= " + iLastErr;
                                Thread.Sleep(2);
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                    break;
            }
        }
        #endregion

        #endregion

        private void labelExit_Click(object sender, EventArgs e)
        {
            Preview_Close();
            LoginOut();
            this.Hide();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            labelDateTime.Text = DateTime.Now.ToString("时间：yyyy-MM-dd HH:mm:ss");
        }

        private void label26_Click(object sender, EventArgs e)
        {

        }
    }
}
